<template>
  <div class="product-list">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>商品列表</span>
          <el-button type="primary" @click="handleAdd">新增商品</el-button>
        </div>
      </template>

      <el-table :data="productList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="商品名称" width="200" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 商品表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formType === 'add' ? '新增商品' : '编辑商品'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="productForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="productForm.category" placeholder="请选择分类">
            <el-option label="电子产品" value="电子产品" />
            <el-option label="服装" value="服装" />
            <el-option label="食品" value="食品" />
            <el-option label="家具" value="家具" />
            <el-option label="图书" value="��书" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="productForm.price"
            :precision="2"
            :step="0.1"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number
            v-model="productForm.stock"
            :min="0"
            :precision="0"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="productForm.status" placeholder="请选择状态">
            <el-option label="在售" value="在售" />
            <el-option label="下架" value="下架" />
            <el-option label="缺货" value="缺货" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getProducts, addProduct, updateProduct, deleteProduct } from '@/api/product'
import type { Product } from '@/api/product'

const loading = ref(true)
const dialogVisible = ref(false)
const formType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const productList = ref<Product[]>([])

const productForm = reactive<Product>({
  name: '',
  category: '',
  price: 0,
  stock: 0,
  status: '在售'
})

const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择商品状态', trigger: 'change' }
  ]
}

const getStatusType = (status: string) => {
  switch (status) {
    case '在售':
      return 'success'
    case '下架':
      return 'info'
    case '缺货':
      return 'danger'
    default:
      return ''
  }
}

const resetForm = () => {
  productForm.name = ''
  productForm.category = ''
  productForm.price = 0
  productForm.stock = 0
  productForm.status = '在售'
}

const loadProducts = async () => {
  try {
    loading.value = true
    const res = await getProducts()
    console.log('Products response:', res)
    if (res.code === 200) {
      productList.value = res.data
    } else {
      ElMessage.error(res.message || '获取商品列表失败')
    }
  } catch (error) {
    console.error('Load products error:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  formType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: Product) => {
  formType.value = 'edit'
  Object.assign(productForm, row)
  dialogVisible.value = true
}

const handleDelete = async (row: Product) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      type: 'warning'
    })
    if (row.id) {
      await deleteProduct(row.id)
      ElMessage.success('删除成功')
      loadProducts()
    }
  } catch {
    // 取消删除
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (formType.value === 'add') {
          const res = await addProduct(productForm)
          if (res.code === 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            loadProducts()
          } else {
            ElMessage.error(res.message || '添加失败')
          }
        } else {
          const res = await updateProduct(productForm)
          if (res.code === 200) {
            ElMessage.success('修改成功')
            dialogVisible.value = false
            loadProducts()
          } else {
            ElMessage.error(res.message || '修改失败')
          }
        }
      } catch (error) {
        console.error('Submit error:', error)
        ElMessage.error(formType.value === 'add' ? '添加失败' : '修改失败')
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  loadProducts()
})
</script>

<style lang="less" scoped>
.product-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style> 